/** 
  新增/编辑实习总结
*/
<template>
  <div class="operate-intern-summary-container">
    <div style="height: 30px;">
      <el-breadcrumb style="float: left;" separator="/">
        <el-breadcrumb-item :to="{ path: '/internSummary' }">
        <span @click="reback()">{{ $t('internSummary.internPlanFinishHappening') }}</span></el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'add'">{{ $t('common.btn.add') }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'edit'">{{ $t('common.btn.edit') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
    </div>
    <el-card shadow="never" v-loading="loading" body-style="padding: 24px;">
      <div class="title">{{ $t('internSummary.internSummary') }}</div>
      <el-divider></el-divider>
      <div class="sub-container">
        <div class="sub-container-title">{{ $t('internSummary.basicInfo') }}</div>
        <table class="table-style-baseinfos">
          <tbody>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.basicName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.name }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.studentId') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.studentId }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.collegeAcademy') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.collegeAcademyStr }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.major') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.majorStr }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.trainingLevel') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.trainingLevelStr }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.trainingCategory') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.trainingCategoryStr }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.degreeType') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.degreeTypeStr }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.formLearning') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.formLearningStr }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.currentGrade') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.currentGrade }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.teacherName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.teacherName }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.majorName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.majorName }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.majorField') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.majorField }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.outsideAdvisorName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.outsideAdvisorName }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.submitFrequency') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.submitFrequency }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.internBaseName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.baseName }}</td>
              <td class="text-right-background-color">{{ $t('internSummary.positionName') }}:</td>
              <td class="text-left-background-none">{{ dataListProp.positionName }}</td>
            </tr>
            <tr>
              <td class="text-right-background-color">{{ $t('internSummary.practiceContent') }}:</td>
              <td class="text-left-background-none" colspan="3">{{ dataListProp.practiceContent }}</td>
            </tr>
          </tbody>
        </table>
        <div class="sub-container-title" style="margin-top: 30px;">
          <span>{{ $t('internSummary.professionPracticePlan') }}</span>
          <!-- 收起 -->
          <span class="collapse-info" v-if="collapse" @click="collapse = !collapse">
            <i class="el-icon-arrow-up"></i><span style="margin-left: 10px;">{{ $t('graduateBase.collapse') }}</span>
          </span>
          <!-- 展开 -->
          <span class="collapse-info" v-else @click="collapse = !collapse">
            <i class="el-icon-arrow-down"></i><span style="margin-left: 10px;">{{ $t('graduateBase.unfold') }}</span>
          </span>
        </div>
        <div class="profession-practice-table" v-show="!collapse">
          <table class="table-style-baseinfo">
            <thead>
              <tr>
                <th class="text-center-background-color">{{ $t('internSummary.reportMonth') }}</th>
                <th class="text-center-background-color">{{ $t('internSummary.content') }}</th>
                <th class="text-center-background-color">{{ $t('internSummary.enclosureFile') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in dataListProp.situationList" :key="index">
                <td class="text-center-background">{{ item.reportMonth }}</td>
                <td style="width: 70%;" class="text-center-background">{{ item.content }}</td>
                <td class="text-center-background">
                  <el-button type="text" @click="downLoadEnclosureFile(item.enclosureFileUrl)">{{ item.enclosureFileName }}</el-button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="sub-container-title">{{ $t('internSummary.practiceSummary') }}</div>
        <el-form class="upload-form" ref="internForm" :model="internForm" label-width="180px">
          <el-form-item prop="summaryContent" :label="$t('internSummary.summaryContent') + ':'" :rules="[{ required: true, message: this.$t('internSummary.requireSummaryContent'), trigger: 'blur' },{ validator: this.checkSpecial, trigger: 'blur'}]">
            <el-input type="textarea" :maxlength="1000" :rows="5" v-model="internForm.summaryContent" clearable style="width: 100%;"></el-input>
          </el-form-item>
          <el-form-item prop="enclosureFile" :label="$t('internSummary.assessFile')+ ':'">
            <el-upload
              v-model="internForm.enclosureFile"
              class="upload-demo"
              action="/api/commonservice/obsfile/uploadfile"
              :data="uploadConfig.data"
              :before-upload="beforeUpload"
              :on-success="handlerUploadSuccess"
              :before-remove="handlerBeforeRemove"
              :on-remove="handlerRemove"
              :on-error="handlerUploadError"
              accept=".bmp, .rar, image/png, image/jpeg, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/pdf, aplication/zip, application/x-zip-compressed"
              multiple
              :limit="5"
              :file-list="uploadConfig.fileList">
              <el-button size="small" type="primary">{{ $t('graduateBase.chooseFile') }}</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div class="operate-footer">
          <el-button @click="cancel()">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="saveInfo()">{{$t('common.btn.save')}}</el-button>
          <el-button type="primary" @click="submitInfo()">{{$t('common.btn.submit')}}</el-button>
        </div>
      </div>
    </el-card>
    <cancel-info 
      :parentInnerVisible="parentInnerVisible" 
      @confirm-and-close="confirmAndClose" 
      @confirm-close="confirmClose" 
      @cancel-to-close="cancelToClose">
    </cancel-info>
  </div>
</template>
<script>
import { downloadfile } from "common/src/api/upload"
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent'
import cancelInfo from '../common/cancelInfo'
export default {
  components: {
    'cancel-info': cancelInfo
  },
  data() {
    return {
      dataListProp: {},
      collapse: false,
      internForm: {
        summaryContent: '',
        enclosureFile: ''
      },
      uploadConfig: {
        fileList: [],
        data: { bucketname: 'face', folderpath: 'file' },
      },
      fileFlag: true,
      applyForm: {
        attachFile: [],
        attachName: []
      },
      parentInnerVisible: false,
      userInfo: {}
    };
  },
  props: {
    internSummaryData: {
      type: Object,
      default: () => {}
    },
    operateMode: {
      type: String,
      default: 'add'
    }
  },
  async created() {
    // 获取当前用户auths权限
    let sessiondata = JSON.parse(localStorage.getItem("sessiondata"));
    if (sessiondata) {
      if (sessiondata.mockUser || sessiondata.user) {
        this.userInfo = sessiondata.mockUser || sessiondata.user;
      }
    }
  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im
      if (regEn.test(value)) {
        callback(new Error(this.$t('graduateBase.specialText')))
      } else {
        callback()
      }
    },
    reback() {
      this.$emit('change-intern-summary-index')
    },
    downLoadEnclosureFile(url) {
      downloadfile(url)
    },
    beforeUpload(file) {
      const fileSizeFlag = file.size && file.size / 1024 / 1024 < 10
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      const uploadFlag = fileType === 'jpg' || fileType === 'jpeg' || fileType === 'png' || fileType === 'bmp' || fileType === 'doc' || fileType === 'docx' || fileType === 'xls' || fileType === 'xlsx' || fileType === 'pdf' || fileType === 'zip' || fileType === 'rar'
      if (!uploadFlag) {
        window.vueApp.showMsgBox({
          message: this.$t("minor.approve.uploadFileError"),
          callback: () => {
          }
        })
      }
      if (!fileSizeFlag) {
        window.vueApp.showMsgBox({
          message: this.$t("minor.approve.uploadSizeError"),
          callback: () => {
          }
        })
      }
      this.fileFlag = (uploadFlag && fileSizeFlag)
      if (!(uploadFlag && fileSizeFlag)) {
        return false
      }
    },
    handlerUploadSuccess(response, file, fileList) {
      let responseCode = response.code
      if (responseCode === 200) {
        this.applyForm.attachFile.push(
          Object.values(response.data)[0].objectkey
        )
        this.applyForm.attachName.push(
          Object.values(response.data)[0].fileName
        )
      }
    },
    handlerBeforeRemove(file, fileList) {
      if (this.fileFlag) {
        return this.$delConfirm().then(_ => {});
      }
    },
    handlerRemove(file, fileList) {
      let index = this.applyForm.attachFile.indexOf(file.url)
      this.applyForm.attachFile.splice(index, 1)
      this.applyForm.attachName.splice(index, 1)
    },
    handlerUploadError(response, file, fileList) {
      this.$message({
        message: this.$t('graduateBase.uploadFail'),
        type: 'error',
      })
    },
    // 取消
    cancel() {
      let allIsEmpty = true
      if (this.operateMode === 'add') {
        for (let key in this.internForm) {
          if (Array.isArray(this.internForm[key]) && this.internForm[key].length > 0) {
            allIsEmpty = false
          }
          if (!Array.isArray(this.internForm[key]) && this.internForm[key]) {
            allIsEmpty = false
          }
        }
      }
      if ((this.operateMode === 'add' && allIsEmpty) || this.operateMode === 'details') {
        this.reback()
      } else {
        this.parentInnerVisible = true
      }
    },
    // 保存
    saveInfo() {
      this.$refs['internForm'].validate((valid) => {
        if (valid) {
          if (this.operateMode === 'add') {
            graduateStudentApi.addInternSummary({
              "applyId": this.dataListProp.applyId,
              "summaryContent": this.internForm.summaryContent,
              "enclosureFileUrl": this.applyForm.attachFile.join(','),
              "enclosureFileName": this.applyForm.attachName.join(',')
            }).then(res => {
              if (res.code === 200) {
                this.$message.success(this.$t('graduateBase.savedSuccessfully'))
                this.reback()
              }
            });
          } else {
            graduateStudentApi.operateInternSummary({
              "id": this.dataListProp.id,
              "applyId": this.dataListProp.applyId,
              "summaryContent": this.internForm.summaryContent,
              "status": "0",
              "enclosureFileUrl": this.applyForm.attachFile.join(','),
              "enclosureFileName": this.applyForm.attachName.join(','),
              "deleteFlag": "0"
            }).then(res => {
              if (res.code === 200) {
                this.$message.success(this.$t('graduateBase.savedSuccessfully'))
                this.reback()
              }
            })
          }
        } else {
          setTimeout(() => {
            let isError = document.getElementsByClassName("is-error");
            if (isError[0] && isError[0] && isError[0].querySelector('input')) {
              isError[0].querySelector('input').focus()
            }
          }, 1)
        }
      });
    },
    // 提交
    async submitInfo() {
      this.$refs['internForm'].validate(async (valid) => {
        if (valid) {
          if (this.operateMode === 'add') {
            if (this.dataListProp.id) {
              this.submitData(this.dataListProp.id);
            } else {
              const res = await graduateStudentApi.addInternSummary({
                "applyId": this.dataListProp.applyId,
                "summaryContent": this.internForm.summaryContent,
                "enclosureFileUrl": this.applyForm.attachFile.join(','),
                "enclosureFileName": this.applyForm.attachName.join(',')
              })
              if (res.code === 200) {
                this.submitData(res.data.id);
              }
            }
          } else {
            const editResponse = await graduateStudentApi.operateInternSummary({
              "id": this.dataListProp.id,
              "applyId": this.dataListProp.applyId,
              "summaryContent": this.internForm.summaryContent,
              "status": "0",
              "enclosureFileUrl": this.applyForm.attachFile.join(','),
              "enclosureFileName": this.applyForm.attachName.join(','),
              "deleteFlag": "0"
            })
            if (editResponse.code === 200) {
              this.submitData(this.dataListProp.id);
            }
          }
        }
      })
    },
    // 提交行为
    submitData(id) {
      graduateStudentApi.submitInternSummary({
        "id": id,
        "outsideAdvisorId": this.dataListProp.outsideAdvisorId,
        "code": this.dataListProp.teacherId
      }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('graduateBase.submitSuccessfully'))
          this.reback()
        }
      })
    },
    // 确定并保存
    confirmAndClose() {
      this.parentInnerVisible = false
      this.saveInfo()
    },
    // 确认关闭提示框
    confirmClose() {
      this.parentInnerVisible = false
      this.reback()
    },
    // 取消关闭
    cancelToClose() {
      this.parentInnerVisible = false
    }
  },
  watch: {
    internSummaryData: {
      handler(newVal) {
        if (newVal) {
          this.dataListProp = JSON.parse(JSON.stringify(newVal))
          if (this.operateMode === 'edit') {
            this.internForm.summaryContent = this.dataListProp.summaryContent
            this.applyForm.attachFile = this.dataListProp.enclosureFileUrl ? this.dataListProp.enclosureFileUrl.split(',') : [];
            this.applyForm.attachName = this.dataListProp.enclosureFileName ? this.dataListProp.enclosureFileName.split(',') : [];
            if (this.applyForm.attachName.length > 0) {
              this.uploadConfig.fileList = this.applyForm.attachName.map((item, index) => {
                return {
                  name: item,
                  url: this.applyForm.attachFile[index]
                };
              });
            }
          }
        }
      },
      deep: true,
      immediate: true
    },
    "applyForm.attachName": {
      handler(newVal) {
        this.internForm.enclosureFile = newVal
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
  .operate-intern-summary-container {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
    .title {
      font-size: 18px;
    }
    .sub-container {
      color: #2a394e;
      padding: 0 20px;
      font-size: 16px;
      .sub-container-title {
        margin-bottom: 20px;
        font-size: 16px;
        .collapse-info {
          margin-left: 55px;
          color: #3a7fe8;
          font-size: 14px;
          cursor: pointer;
        }
      }
    }
    .table-style-baseinfos {
      table-layout: fixed;
      word-break: break-all;
      background-color: rgba(210, 212, 214, 1);
      box-sizing: border-box;
      border-width: 0.5px;
      border-style: solid;
      border-color: rgba(210, 212, 214, 1);
      border-radius: 0px;
      -moz-box-shadow: none;
      -webkit-box-shadow: none;
      box-shadow: none;
      width: 100%;
      font-weight: 401;
      font-style: normal;
      font-size: 14px;
      color: #8896a7;
      margin-bottom: 20px;
      td {
        width: 25%;
        background-color: rgba(255, 255, 255, 1);
        border: none;
        border-radius: 0px;
        -moz-box-shadow: none;
        -webkit-box-shadow: none;
        box-shadow: none;
        font-weight: 401;
        font-style: normal;
        font-size: 14px;
        color: #2b3b4e;
        height: 32px;
        padding: 0 10px;
      }
      .text-right-background-color {
        background-color: #fdfeff4d;
        text-align: right;
      }
      .text-left-background-none {
        text-align: left;
      }
    }
    .table-style-baseinfo {
      table-layout: fixed;
      word-break: break-all;
      background-color: rgba(210, 212, 214, 1);
      box-sizing: border-box;
      border-width: 0.5px;
      border-style: solid;
      border-color: rgba(210, 212, 214, 1);
      border-radius: 0px;
      -moz-box-shadow: none;
      -webkit-box-shadow: none;
      box-shadow: none;
      width: 100%;
      font-weight: 401;
      font-style: normal;
      font-size: 14px;
      color: #8896a7;
      margin-bottom: 20px;
      .text-right-background-color {
        background-color: #fdfeff4d;
        text-align: right;
      }
      td {
        background-color: rgba(255, 255, 255, 1);
        border: none;
        border-radius: 0px;
        -moz-box-shadow: none;
        -webkit-box-shadow: none;
        box-shadow: none;
        font-weight: 401;
        font-style: normal;
        font-size: 14px;
        color: #2b3b4e;
        height: 32px;
        padding: 0 10px;
      }
    }
    .operate-footer {
      text-align: right;
    }
  }
</style>